<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑角色' : '新增角色' }}</span>
          <el-button @click="goBack" type="text">返回</el-button>
        </div>
      </template>

      <el-form ref="roleFormRef" :model="form" :rules="rules" label-width="120px" style="max-width: 800px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入角色编码" :disabled="isEdit" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择角色类型" style="width: 100%">
                <el-option label="系统角色" value="SYSTEM" />
                <el-option label="业务角色" value="BUSINESS" />
                <el-option label="自定义角色" value="CUSTOM" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio value="ACTIVE">启用</el-radio>
                <el-radio value="INACTIVE">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据权限" prop="dataScope">
              <el-select v-model="form.dataScope" placeholder="请选择数据权限范围" style="width: 100%">
                <el-option label="全部数据权限" value="ALL" />
                <el-option label="自定义数据权限" value="CUSTOM" />
                <el-option label="部门数据权限" value="DEPT" />
                <el-option label="部门及以下数据权限" value="DEPT_AND_CHILD" />
                <el-option label="仅本人数据权限" value="SELF" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="角色描述" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                :rows="3"
                placeholder="请输入角色描述"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="菜单权限" prop="menuIds">
              <div class="permission-tree">
                <div class="tree-header">
                  <el-checkbox
                    v-model="checkAll"
                    :indeterminate="isIndeterminate"
                    @change="handleCheckAllChange"
                  >
                    全选/全不选
                  </el-checkbox>
                  <div class="tree-actions">
                    <el-button size="small" @click="expandAll">展开全部</el-button>
                    <el-button size="small" @click="collapseAll">折叠全部</el-button>
                  </div>
                </div>
                <el-tree
                  ref="menuTreeRef"
                  :data="menuTree"
                  :props="{ children: 'children', label: 'name' }"
                  show-checkbox
                  node-key="id"
                  :default-checked-keys="form.menuIds"
                  @check="handleMenuCheck"
                  class="menu-tree"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getRoleDetail, createRole, updateRole, getMenuTree } from '@/api/user'

const route = useRoute()
const router = useRouter()

// 响应式数据
const roleFormRef = ref()
const menuTreeRef = ref()
const loading = ref(false)
const menuTree = ref([])
const checkAll = ref(false)
const isIndeterminate = ref(false)

// 表单数据
const form = reactive({
  id: undefined,
  name: '',
  code: '',
  type: 'BUSINESS',
  sort: 0,
  status: 'ACTIVE',
  dataScope: 'DEPT',
  description: '',
  menuIds: []
})

// 计算属性
const isEdit = computed(() => !!route.params.id)

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择角色类型', trigger: 'change' }
  ],
  dataScope: [
    { required: true, message: '请选择数据权限范围', trigger: 'change' }
  ]
})

// 获取菜单树
const loadMenuTree = async () => {
  try {
    const response = await getMenuTree()
    if (response.code === 200) {
      menuTree.value = response.data
    }
  } catch (error) {
    console.error('获取菜单树失败:', error)
  }
}

// 获取角色详情
const loadRoleDetail = async () => {
  if (!isEdit.value) return
  
  try {
    const response = await getRoleDetail(route.params.id)
    if (response.code === 200) {
      Object.assign(form, response.data)
      // 设置菜单权限
      await nextTick()
      if (menuTreeRef.value && form.menuIds.length > 0) {
        menuTreeRef.value.setCheckedKeys(form.menuIds)
        updateCheckAllStatus()
      }
    }
  } catch (error) {
    console.error('获取角色详情失败:', error)
    ElMessage.error('获取角色详情失败')
  }
}

// 处理菜单选择
const handleMenuCheck = () => {
  const checkedKeys = menuTreeRef.value.getCheckedKeys()
  const halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys()
  form.menuIds = [...checkedKeys, ...halfCheckedKeys]
  updateCheckAllStatus()
}

// 更新全选状态
const updateCheckAllStatus = () => {
  const checkedCount = menuTreeRef.value.getCheckedKeys().length
  const totalCount = getAllMenuIds(menuTree.value).length
  
  checkAll.value = checkedCount === totalCount
  isIndeterminate.value = checkedCount > 0 && checkedCount < totalCount
}

// 获取所有菜单ID
const getAllMenuIds = (menus) => {
  let ids = []
  menus.forEach(menu => {
    ids.push(menu.id)
    if (menu.children && menu.children.length > 0) {
      ids = ids.concat(getAllMenuIds(menu.children))
    }
  })
  return ids
}

// 全选/全不选
const handleCheckAllChange = (checked) => {
  if (checked) {
    const allIds = getAllMenuIds(menuTree.value)
    menuTreeRef.value.setCheckedKeys(allIds)
    form.menuIds = allIds
  } else {
    menuTreeRef.value.setCheckedKeys([])
    form.menuIds = []
  }
  isIndeterminate.value = false
}

// 展开全部
const expandAll = () => {
  const allIds = getAllMenuIds(menuTree.value)
  allIds.forEach(id => {
    menuTreeRef.value.store.nodesMap[id].expanded = true
  })
}

// 折叠全部
const collapseAll = () => {
  const allIds = getAllMenuIds(menuTree.value)
  allIds.forEach(id => {
    menuTreeRef.value.store.nodesMap[id].expanded = false
  })
}

// 提交表单
const submitForm = () => {
  roleFormRef.value?.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 获取最新的菜单权限
        const checkedKeys = menuTreeRef.value.getCheckedKeys()
        const halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys()
        form.menuIds = [...checkedKeys, ...halfCheckedKeys]
        
        if (isEdit.value) {
          await updateRole(form.id, form)
          ElMessage.success('更新成功')
        } else {
          await createRole(form)
          ElMessage.success('创建成功')
        }
        goBack()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  roleFormRef.value?.resetFields()
  menuTreeRef.value?.setCheckedKeys([])
  form.menuIds = []
  checkAll.value = false
  isIndeterminate.value = false
}

// 返回列表
const goBack = () => {
  router.push('/user/role')
}

// 页面加载
onMounted(async () => {
  await loadMenuTree()
  await loadRoleDetail()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.permission-tree {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  
  .tree-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    background: #f5f7fa;
    border-bottom: 1px solid #dcdfe6;
    
    .tree-actions {
      display: flex;
      gap: 8px;
    }
  }
  
  .menu-tree {
    max-height: 400px;
    overflow-y: auto;
    padding: 12px;
  }
}
</style>
